package com.knowledge.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.knowledge.common.constant.GlobalConstant;
import com.knowledge.common.enums.ErrorCode;
import com.knowledge.common.enums.NewsTypeEnum;
import com.knowledge.common.enums.UserRoleEnum;
import com.knowledge.dao.dos.Archives;
import com.knowledge.dao.entity.*;
import com.knowledge.dao.mapper.ArticleBodyMapper;
import com.knowledge.dao.mapper.ArticleMapper;
import com.knowledge.service.*;
import com.knowledge.utils.TemplateParserUtil;
import com.knowledge.utils.UserThreadLocal;
import com.knowledge.vo.ArticleBodyVo;
import com.knowledge.vo.ArticleVo;
import com.knowledge.vo.Result;
import com.knowledge.vo.params.ArticleFavoriteParam;
import com.knowledge.vo.params.ArticleParam;
import com.knowledge.vo.params.PageParams;
import com.knowledge.vo.params.ShareParam;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author zzz
 * @create 2022-02-10 16:28
 */
@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements ArticleService {
    @Resource
    private ArticleMapper articleMapper;
    @Resource
    private TagService tagService;
    @Resource
    private SysUserService sysUserService;
    @Resource
    private ArticleBodyMapper articleBodyMapper;
    @Resource
    private CategoryService categoryService;
    @Resource
    private ThreadService threadService;

    @Autowired
    private NewsService newsService;

    @Autowired
    private ArticleFavoriteService articleFavoriteService;

//    @Autowired
//    private ArticleTagMapper articleTagMapper;


//    @Override
//    public Result listArticle(PageParams pageParams) {
//        /**
//         * 1. 分页查询article数据库表
//         */
//        Page<Article> page = new Page<>(pageParams.getPage(), pageParams.getPageSize());
//        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
//        //查询文章的参数 加上分类id, 判断不为空 加上分类条件
//        if(pageParams.getCategoryId()!=null){
//            queryWrapper.eq(Article::getCategoryId,pageParams.getCategoryId());
//        }
//        ArrayList<Long> articleIdList = new ArrayList<>();
//        if(pageParams.getTagId()!=null){
//            /**加入标签条件查询
//             * article表中并没有tag字段 一篇文章有多个标签
//             * article_tag article_id 1:n tag_id
//             * 我们需要利用一个全新的属于文章标签的queryWrapper将这篇文章article_Tag查出来,保存到一个list当中
//             * 然后再根据queryWrapper的in方法选择我们需要的标签即可
//             */
//            LambdaQueryWrapper<ArticleTag> articleTagLambdaQueryWrapper = new LambdaQueryWrapper<>();
//            articleTagLambdaQueryWrapper.eq(ArticleTag::getTagId,pageParams.getTagId());
//            List<ArticleTag> articleTags = articleTagMapper.selectList(articleTagLambdaQueryWrapper);
//            for (ArticleTag articleTag : articleTags) {
//                articleIdList.add(articleTag.getArticleId());
//            }
//            if(articleTags.size()>0){
//                queryWrapper.in(Article::getId,articleIdList);
//            }
//        }
//        //按照创建日期倒叙排序
//        //是否置顶排序
//        queryWrapper.orderByDesc(Article::getWeight, Article::getCreateDate);
//        Page<Article> articlePage = articleMapper.selectPage(page, queryWrapper);
//        List<Article> records = articlePage.getRecords();
//        //能直接返回吗 需要一个vo对象来存储筛选显示的数据
//        List<ArticleVo> articleVoList = copyList(records,true,true);
//        return Result.success(articleVoList);
//    }

    @Override
    public Result listArticle(PageParams pageParams) {
        Page<Article> page = new Page<>(pageParams.getPage(), pageParams.getPageSize());

        //获取用户
        SysUser sysUser = UserThreadLocal.get();
        Long loginUserId = sysUser == null ? null : sysUser.getId();
        //如果查询的是收藏列表，则查询收藏的文章
        Integer favorite = pageParams.getFavorite();

        IPage<Article> articleIPage = articleMapper.listArticle(page,
                pageParams.getCategoryId(),
                pageParams.getTagId(),
                pageParams.getYear(),
                pageParams.getMonth(),
                favorite,
                loginUserId,
                pageParams.getMyArticleFlag(),
                pageParams.getKeyword());
        List<Article> records = articleIPage.getRecords();

        //转换对象
        List<ArticleVo> list = copyList(records,true, true, checkIsAdmin(), loginUserId);
        if (loginUserId != null){
            //登录情况下处理情况
            if (GlobalConstant.YES.equals(favorite)){
                //查询了我的收藏(设置已收藏的标识)
                list.forEach(a->a.setFavorite(GlobalConstant.YES));
            }else {
                //文章ID
                List<Long> articleIds = list.stream().map(ArticleVo::getId).collect(Collectors.toList());
                //登录情况关联是否收藏
                ArticleFavoriteParam articleFavoriteParam = new ArticleFavoriteParam();
                articleFavoriteParam.setUserId(loginUserId);
                articleFavoriteParam.setArticleIds(articleIds);
                List<ArticleFavorite> articleFavorites = articleFavoriteService.listArticleFavorite(articleFavoriteParam);
                //设置是否收藏
                for (ArticleVo articleVo : list){
                    for (ArticleFavorite articleFavorite : articleFavorites){
                        if (articleVo.getId().equals(articleFavorite.getArticleId())){
                            articleVo.setFavorite(GlobalConstant.YES);
                            break;
                        }
                    }
                }
            }
        }
        //关联用户信息
        if (CollUtil.isNotEmpty(list)) {
            relationUserInfo(list);
        }
        return Result.success(list);
    }

     /**
     　* @description: 关联用户信息
     　* @param ${tags}
     　* @return ${return_type}
     　* @throws
     　* @author zzz
     　* @date 2022-03-15 14:40
     */
    private void relationUserInfo(List<ArticleVo> list){
        List<Long> userIds = list.stream().map(ArticleVo::getAuthorId).collect(Collectors.toList());
        List<SysUser> userList = sysUserService.listByIds(userIds);
        if (userList != null && userList.size() > 0){
            Map<Long, SysUser> userMap = userList.stream().collect(Collectors.toMap(SysUser::getId, Function.identity(), (v,v2)->v2));
            for (ArticleVo av : list){
                SysUser sysUser = userMap.get(av.getAuthorId());
                if (sysUser != null){
                    av.setAuthor(sysUser.getNickname());
                    av.setAvatar(sysUser.getAvatar());
                }
            }
        }
    }

    /**
     * 是否是管理员
     * @return
     */
    private boolean checkIsAdmin() {
        try {
            return 1 == UserThreadLocal.get().getAdmin();
        }catch (Exception ignored) {
            return false;
        }
    }

    @Override
    public Result hotArticle(int limit) {
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Article::getViewCounts).select(Article::getId,Article::getTitle).last("limit "+ limit);
        List<Article> articles = articleMapper.selectList(queryWrapper);
        return Result.success(copyList(articles,false,false, false, null));
    }

    @Override
    public Result newArticle(int limit) {
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Article::getCreateDate).select(Article::getId,Article::getTitle).last("limit "+ limit);
        List<Article> articles = articleMapper.selectList(queryWrapper);
        return Result.success(copyList(articles,false,false, false, null));
    }

    @Override
    public Result listArchives() {
        List<Archives> archivesList = articleMapper.listArchives();
        return Result.success(archivesList);

    }

    /**
     * 1. 根据id查询 文章信息
     * 2. 根据bodyid和catagroryid 去做关联查询
     * @param id
     * @return
     */
    @Override
    public Result findArticleById(long id) {
        Article article = articleMapper.selectById(id);
        if (article == null) {
            return Result.fail(ErrorCode.ARTICLE_NOT_EXIST.getCode(), ErrorCode.ARTICLE_NOT_EXIST.getMsg());
        }
        ArticleVo articleVo = copy(article,true,true,true,true);
        //查看玩文章了,新增阅读数
        //查看完文章之后,本应该直接返回数据了 这时候租了一个更新操作,更新时加写锁,阻塞了其他的读操作,性能就会比较低
        //更新增加了此次接口的 耗时 如果一旦更新出问题 不能影响 查看文章的操作
        //使用线程池 可以把更新操作扔到线程池中执行 和主线程就不相关了
        threadService.updateArticleViewCount(articleMapper,article);
        return Result.success(articleVo);
    }


    private List<ArticleVo> copyList(List<Article> records, boolean isTag, boolean isAuthor, boolean admin, Long loginUserId) {
        ArrayList<ArticleVo> articleVos = new ArrayList<>();
        for (Article record : records) {
            articleVos.add(copy(record,isTag,isAuthor, admin, loginUserId));
        }
        return articleVos;
    }

    private ArticleVo copy(Article article,boolean isTag,boolean isAuthor, boolean admin, Long loginUserId) {
        ArticleVo articleVo = new ArticleVo();
        BeanUtils.copyProperties(article, articleVo);
        articleVo.setCreateDate(new DateTime(article.getCreateDate()).toString("yyyy-MM-dd HH:mm:ss"));
        if(isTag){
            articleVo.setTags(tagService.findTagsByArticleId(article.getId()));
        }
        if(isAuthor){
            articleVo.setAuthor(sysUserService.findUserById(article.getAuthorId()).getNickname());
        }

        if (loginUserId != null && Objects.equals(article.getAuthorId(), loginUserId)) {
            articleVo.setCanDelete(1);
        }

        if (admin) {
            articleVo.setAdmin(1);
            articleVo.setCanDelete(1);
        }
        return articleVo;
    }

    private ArticleVo copy(Article article,boolean isTag,boolean isAuthor,boolean isBody,boolean isCategory) {
        ArticleVo articleVo = new ArticleVo();
        BeanUtils.copyProperties(article, articleVo);

        articleVo.setCreateDate(new DateTime(article.getCreateDate()).toString("yyyy-MM-dd HH:mm:ss"));
        if(isTag){
            articleVo.setTags(tagService.findTagsByArticleId(article.getId()));
        }
        if(isAuthor){
            articleVo.setAuthor(sysUserService.findUserById(article.getAuthorId()).getNickname());
        }
        if(isBody){
            Long articleBodyId = article.getBodyId();
            articleVo.setBody(findArticleBodyById(articleBodyId));
        }
        if(isCategory){
            Long categoryId = article.getCategoryId();
            articleVo.setCategory(categoryService.findCategoryById(categoryId));
        }
        return articleVo;
    }


    @Override
    public ArticleBodyVo findArticleBodyById(Long id) {
        ArticleBody articleBody = articleBodyMapper.selectById(id);
        ArticleBodyVo articleBodyVo = new ArticleBodyVo();
        articleBodyVo.setContent(articleBody.getContent());
        return articleBodyVo;
    }

    @Override
    public Result publishArticle(ArticleParam articleParam) {
        //发布文章 前提 需要已登录 所以需要将接口加入拦截器中
        SysUser sysUser = UserThreadLocal.get();
        /**
         * 1.发布文章 实际上就是 构建一个Article对象 然后再插入表中
         * 2. 作者id 当前登陆用户的id
         * 3. 标签 要将标签加入到关联列表当中
         * 4. body 内容存储 article bodyId
         */
        Article article = new Article();
        article.setAuthorId(sysUser.getId());

        //管理员发布的文章默认为管理员的标签，用户发布的为用户分类
        article.setCategoryId(getArticleCategory(sysUser.getAdmin()));
        article.setCreateDate(System.currentTimeMillis());
        article.setViewCounts(0);
        article.setSummary(articleParam.getSummary());
        article.setTitle(articleParam.getTitle());
        article.setCommentCounts(0);
        article.setWeight(Article.ARTICLE_COMMON);
        article.setBodyId(-1L);
        //文章id自动生成 雪花算法
        articleMapper.insert(article);

        //tags
        saveTags(articleParam.getTags(), article.getId(), sysUser.getAdmin());

        //body
        ArticleBody articleBody = new ArticleBody();
        articleBody.setArticleId(article.getId());
        articleBody.setContent(articleParam.getBody().getContent());
        articleBody.setContentHtml(articleParam.getBody().getContentHtml());
        articleBodyMapper.insert(articleBody);


        //根据结构 我们需要再article中设置bodyId Mybatis-plus中会将更新的数据赋值给对象
        //这里的id我们并没有设置 而是雪花算法 插入之后 数据库的id赋值给了对象 我们可以通过这个对象获取
        article.setBodyId(articleBody.getId());

        //将文章更新
        articleMapper.updateById(article);


        //接口要求返回articleVo对象
        ArticleVo articleVo = new ArticleVo();
        articleVo.setId(article.getId());
        return Result.success(articleVo);
    }

    private Long getArticleCategory(Integer admin) {
        return categoryService.getOrSaveCategory(admin);
    }

    private void saveTags(String tagName, Long id, Integer admin) {

        //查询标签
        Tag tag = tagService.getOrSaveTag(tagName);

        ArticleTag articleTag = new ArticleTag();
        articleTag.setArticleId(id);
        articleTag.setTagId(tag.getId());
        tagService.save(articleTag);

        //如果是管理员发布的文章，默认加上官方的标签
        if(UserRoleEnum.ADMIN.getType().equals(admin)) {
            Tag t = tagService.getOrSaveTag(GlobalConstant.TAG_OFFICIAL);
            ArticleTag ta = new ArticleTag();
            ta.setArticleId(id);
            ta.setTagId(t.getId());
            tagService.save(ta);
        }
    }

    @Override
    public Result pushTop(long id) {
        //查询最大权重的文章id，并把权重加1
        int weight = articleMapper.getMaxWeight();
        articleMapper.pushTop(weight, id);
        return Result.success(null);
    }

    @Override
    public Result delete(long id) {
        int i = articleMapper.deleteById(id);
        return Result.success(i);
    }

    @Override
    public Integer addShareArticle(ShareParam shareParam) {
        Article article = getById(shareParam.getArticleId());
        if (article != null){
            //添加分享消息
            NewsEntity newsEntity = new NewsEntity();
            newsEntity.setUserId(shareParam.getFriendUserId());
            newsEntity.setFromUserId(shareParam.getUserId());
            newsEntity.setType(NewsTypeEnum.SHARE.getType());
            //扩展参数
            Map<String, Object> extendParams = new HashMap<>();
            extendParams.put("id", article.getId());
            newsEntity.setExtendParams(JSON.toJSONString(extendParams));
            String contentTemplate = NewsTypeEnum.SHARE.getContentTemplate();
            Map<String, String> contentMap = new HashMap<>();
            contentMap.put("userName", shareParam.getUserName());
            contentMap.put("title", article.getTitle());
            newsEntity.setContent(TemplateParserUtil.parse(contentTemplate, contentMap));
            newsService.addNews(newsEntity);
            return GlobalConstant.YES;
        }else {
            return GlobalConstant.NO;
        }
    }
}
